import { ResponseCode } from "@/enum/appEnum";

const responseBody: { [propName: string]: any } = {
  msg: "",
  timestamp: 0,
  datas: null,
  code: "",
};

export const builder = (
  data: any,
  msg: string,
  code: number | string,
  headers = {}
) => {
  responseBody.datas = data;
  if (msg !== undefined && msg !== null) {
    responseBody.msg = msg;
  }
  if (code !== undefined && code !== "") {
    responseBody.code = code;
    responseBody._status = code === ResponseCode.success ? 200 : code;
  }
  if (
    headers !== null &&
    typeof headers === "object" &&
    Object.keys(headers).length > 0
  ) {
    responseBody._headers = headers;
  }
  responseBody.timestamp = new Date().getTime();
  return responseBody;
};

export const getQueryParameters = (options: { [propName: string]: any }) => {
  const url = options.url;
  const search = url.split("?")[1];
  if (!search) {
    return {};
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"') +
      '"}'
  );
};

export const getBody = (options: { [propName: string]: any }) => {
  return options.body && JSON.parse(options.body);
};
